
#include <sys/socket.h> // Add this header for socket()
#include <netinet/in.h> // Often needed for sockaddr_in, etc>
#include <unistd.h>     // For close()
#include <fcntl.h>      // For fcntl()

#include "Acceptor.h"
#include "Logger.h"
#include "InetAddress.h"


static int newConnectionSocket()
{
    // Example: create a non-blocking IPv4 TCP socket
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        LOG_FATAL("new connect error");
    }

    return sockfd;
}

Acceptor::Acceptor(EventLoop *loop, const InetAddress &listenAddr, bool reuseport)
    : loop_(loop), acceptSocket_(newConnectionSocket()), acceptChannel_(loop, acceptSocket_.fd()), newConnectionCallback_(nullptr), listenning_(false)
{
    acceptSocket_.setReusePort(true);
    acceptSocket_.setReuseAddr(true);
    acceptSocket_.bindAddress(listenAddr);

    // 这个callback 为 先接受到线程连接，在执行newConnectionCallback_(即分发给workloop处理线程连接)
    acceptChannel_.setReadCallback(std::bind(&Acceptor::handleRead, this));
}
Acceptor::~Acceptor()
{
    acceptChannel_.disableAll();
    acceptChannel_.remove();
}

void Acceptor::listen()
{
    listenning_ = true;
    acceptSocket_.listen();
    acceptChannel_.enableReading();
}

void Acceptor::handleRead()
{
    InetAddress peerAddr;
    int connfd = acceptSocket_.accept(&peerAddr);
    if (connfd > 0)
    {
        // 设置为非阻塞的
        int flags = ::fcntl(connfd, F_GETFL, 0);
        ::fcntl(connfd, F_SETFL, flags | O_NONBLOCK);
        if (newConnectionCallback_)
        {
            // 其实这个函数就是做分发的
            newConnectionCallback_(connfd, peerAddr);
        }
        else
        {
            // 没有回调即不处理线程连接，一般会有的
            LOG_INFO("handleRead not have callback");
            ::close(connfd);
        }
    }
    else
    {
        LOG_ERROR("handleRead error");
    }
}